package brick.has.web;

import brick.has.bean.ApiResponse;
import brick.has.entity.Device;
import brick.has.service.DeviceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.http.HttpResponse;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/device")
public class DeviceController {

    private final RestTemplate restTemplate;

    public DeviceController() {
        this.restTemplate = new RestTemplate();
    }

    @Autowired
    private DeviceService deviceService;

    @RequestMapping("/map")
    public ApiResponse getDeviceMap() {
        return ApiResponse.success(deviceService.getDeviceMap());
    }

    @RequestMapping("/report")
    public ApiResponse report(@RequestBody Device device) {
        deviceService.report(device);
        return ApiResponse.success();
    }

    @RequestMapping("/control")
    public String control(@RequestBody Map<String, Object> data) throws JsonProcessingException {
        Device device = deviceService.getDeviceMap().get(data.get("id"));
        data.remove("id");
        return post(String.format("http://%s/api/v1/control", device.getUrl()), new JsonMapper().writeValueAsString(data));
    }

    public String post(String url, String body) {
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        // 创建 HttpEntity 对象
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);

        // 发送 POST 请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 打印响应
        System.out.println("Response Status Code: " + responseEntity.getStatusCode());
        System.out.println("Response Body: " + responseEntity.getBody());

        return responseEntity.getBody();
    }
}
